import { defineStore } from 'pinia';
import { computed, ref } from 'vue';

// 创建自定义持久化存储
const storage = {
  getItem: (key) => uni.getStorageSync(key),
  setItem: (key, value) => uni.setStorageSync(key, value),
  removeItem: (key) => uni.removeStorageSync(key),
};

// 创建自定义持久化配置
const createPersistConfig = (key) => ({
  key,
  storage,
});

export const useCartStore = defineStore(
  'cart',
  () => {
    // 响应式状态
    const cartList = ref(storage.getItem('cartList') || []);
    const selectedList = ref([]);
    const historyList = ref(storage.getItem('historyList') || []);
    const temporaryAddress = ref(storage.getItem('temporaryAddress') || null);

    // 计算属性
    const totalCount = computed(() =>
      cartList.value.reduce((total, item) => total + (item.number || 0), 0)
    );

    const cartNumber = computed(() => cartList.value.length);

    const totalPrice = computed(() =>
      cartList.value
        .reduce(
          (total, item) => total + (item.number || 0) * (item.sell_price || 0),
          0
        )
        .toFixed(2)
    );
    // 已选商品总价
    const selectedTotalPrice = computed(() =>
      cartList.value
        .filter((item) => selectedList.value.includes(item.id))
        .reduce(
          (total, item) => total + (item.number || 0) * (item.sell_price || 0),
          0
        )
        .toFixed(2)
    );
    // 已选商品数量
    const selectedCount = computed(() =>
      cartList.value
        .filter((item) => selectedList.value.includes(item.id))
        .reduce((total, item) => total + (item.number || 0), 0)
    );
    // 是否全选
    const isAllSelected = computed(
      () =>
        cartList.value.length > 0 &&
        selectedList.value.length === cartList.value.length
    );

    // 方法
    const addToCart = (goods) => {
      if (goods.stock_quantity <= 0) {
        uni.showToast({
          title: '商品库存不足',
          icon: 'none',
        });
        return false;
      }
      // 判断商品是否存在
      const existItem = cartList.value.find((item) => item.id === goods.id);
      if (existItem) {
        if (existItem.number + (goods.number || 1) > goods.stock_quantity) {
          uni.showToast({
            title: '超出库存数量',
            icon: 'none',
          });
          return false;
        }
        existItem.number += goods.number || 1;
      } else {
        cartList.value.push({
          ...goods,
          number: goods.number || 1,
          selected: true, // 修改為默認選中
        });
        // 將新添加的商品ID加入已選擇列表
        selectedList.value.push(goods.id);
      }
      storage.setItem('cartList', cartList.value);
      return true;
    };
    // 从购物车中移除商品
    const removeFromCart = (goodsId) => {
      const index = cartList.value.findIndex((item) => item.id === goodsId);
      if (index > -1) {
        cartList.value.splice(index, 1);
        selectedList.value = selectedList.value.filter((id) => id !== goodsId);
        storage.setItem('cartList', cartList.value);
      }
    };
    // 更新购物车商品数量
    const updateCartItemNumber = (goodsId, number) => {
      const item = cartList.value.find((item) => item.id === goodsId);
      if (item) {
        if (number > item.stock_quantity) {
          uni.showToast({
            title: '超出库存数量',
            icon: 'none',
          });
          return false;
        }
        item.number = number;
        storage.setItem('cartList', cartList.value);
        return true;
      }
      return false;
    };
    // 清空购物车
    const clearCart = () => {
      cartList.value = [];
      selectedList.value = [];
      storage.setItem('cartList', cartList.value);
    };
    // 切换商品选中状态
    const toggleItemSelected = (goodsId) => {
      const item = cartList.value.find((item) => item.id === goodsId);
      if (item) {
        item.selected = !item.selected;
        if (item.selected) {
          selectedList.value.push(goodsId);
        } else {
          selectedList.value = selectedList.value.filter(
            (id) => id !== goodsId
          );
        }
        storage.setItem('cartList', cartList.value);
        return true;
      }
      return false;
    };
    // 切换全选状态
    const toggleAllSelected = () => {
      const allSelected = isAllSelected.value;
      cartList.value.forEach((item) => {
        item.selected = !allSelected;
      });
      selectedList.value = allSelected
        ? []
        : cartList.value.map((item) => item.id);
      storage.setItem('cartList', cartList.value);
    };

    const setTemporaryAddress = (address) => {
      temporaryAddress.value = address;
      storage.setItem('temporaryAddress', address);
    };
    // 清空临时地址
    const clearTemporaryAddress = () => {
      temporaryAddress.value = null;
      storage.removeItem('temporaryAddress');
    };

    const addToHistory = (goods) => {
      const existIndex = historyList.value.findIndex(
        (item) => item.id === goods.id
      );
      if (existIndex > -1) {
        historyList.value.splice(existIndex, 1);
      }
      historyList.value.unshift(goods);
      if (historyList.value.length > 50) {
        historyList.value.pop();
      }
      storage.setItem('historyList', historyList.value);
    };

    const clearHistory = () => {
      historyList.value = [];
      storage.removeItem('historyList');
    };

    return {
      // 状态
      cartList,
      selectedList,
      historyList,
      temporaryAddress,

      // 计算属性
      totalCount,
      cartNumber,
      totalPrice,
      selectedTotalPrice,
      selectedCount,
      isAllSelected,

      // 方法
      addToCart,
      removeFromCart,
      updateCartItemNumber,
      clearCart,
      toggleItemSelected,
      toggleAllSelected,
      setTemporaryAddress,
      clearTemporaryAddress,
      addToHistory,
      clearHistory,
    };
  },
  {
    persist: createPersistConfig('cart'),
  }
);
